//
//  PhotoBrowing.swift
//  ServiceHelper
//
//  Created by Xuedan on 15/12/14.
//  Copyright © 2015年 Stan Wu. All rights reserved.
//

import UIKit


class PhotoBrowing: UIView {

    var imageView:SWImageView!
    var lastScale:CGFloat!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // Initialization code
        lastScale = 1.0
        let ScreenWidth = UIScreen.mainScreen().bounds.width
        let ScreenHeight = UIScreen.mainScreen().bounds.height
        self.backgroundColor = UIColor.blackColor()
        
        self.imageView = SWImageView()
        self.backgroundColor = UIColor.whiteColor()
        self.imageView.frame = CGRectMake(0,(ScreenWidth-ScreenHeight)/2,ScreenWidth,ScreenHeight)
        
        let gr1:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowing.handleTapGesture(_:)))
        let gr2:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PhotoBrowing.handleTapGesture(_:)))
        gr1.numberOfTapsRequired = 1
        gr1.requireGestureRecognizerToFail(gr2)//这里保证双击的时候不会出发单击时间
        gr2.numberOfTapsRequired = 2
        self.imageView.userInteractionEnabled = true
        self.imageView.addGestureRecognizer(gr1)
        self.imageView.addGestureRecognizer(gr2)
        
        let pin:UIPinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: #selector(PhotoBrowing.handlePinchGesture(_:)))
        self.imageView.addGestureRecognizer(pin)
        
        
        self.addSubview(self.imageView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    单击self消失
    双击self.imageView放大和缩小
    */
    func handleTapGesture(sender:UITapGestureRecognizer){
        let touchCount:Int = sender.numberOfTapsRequired
        switch touchCount {
        case 1:
            dismiss()
        case 2:
            self.handleDoubleClick(sender)
        default:print("")
        }
    }
    
    /*
    手势：捏
    */
    func handlePinchGesture(sender:UIGestureRecognizer){
        let factor:CGFloat = (sender as! UIPinchGestureRecognizer).scale
        sender.view!.transform = CGAffineTransformMakeScale(factor
            , factor)
    }
    
    
    //self消失
    func dismiss(){
        
        UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            self.backgroundColor = UIColor(white:1, alpha: 0)
            self.imageView.alpha = 0
            }, completion: {(value:Bool) in
                self.removeFromSuperview()
        })
    }
    //双击放大和缩小
    func handleDoubleClick(sender:UIGestureRecognizer){
        //.ScaleAspectFit是原比例
        if sender.view!.contentMode == .ScaleAspectFit {
            sender.view!.contentMode = .Center
        }else{
            sender.view!.contentMode = .ScaleAspectFit
        }
    }

}
